package com.study.manage.mvc.v2;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.manage.dal.UserOrganizaRepository;
import com.study.manage.dal.UserRepository;
import com.study.manage.dal.UserRoleRepository;
import com.study.manage.domain.User;
import com.study.manage.domain.UserOrganiza;
import com.study.manage.domain.enumm.LiveDieState;
import com.study.manage.domain.enumm.UserRoleType;
import com.study.manage.domain.enumm.UserType;
import com.study.manage.domain.enumm.VerifyState;
import com.study.manage.dto.AjaxResponse;
import com.study.manage.dto.SessionUser;
import com.study.manage.exception.ManageException;
import com.study.manage.mvc.common.BaseController;

@Controller
@RequestMapping("v2")
public class V2LoginController extends BaseController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserOrganizaRepository userOrganizaRepository;

    /**
     * 机构认证（登陆）
     * 
     */
    @RequestMapping(path = "login", method = RequestMethod.GET)
    public String org_login() {
        return "v2/login";
    }

    /**
     * 退出（重新登陆）
     * 
     */
    @RequestMapping(path = "logout", method = RequestMethod.GET)
    public void org_logout() throws Exception {

        this.logout(request);
        response.sendRedirect(request.getContextPath() + "/org/login");
    }

    /**
     * 登陆验证
     * 
     */
    @ResponseBody
    @RequestMapping(path = "login-login", method = RequestMethod.POST)
    public AjaxResponse org_login(String userName, String password) {
        User user = userRepository.findByPhone(userName);
        if (user == null || !user.hashPassword.equals(hashPassword(password, scret, user.salt))) {
            throw new ManageException("用户名或密码错误");
        }
        if (user.state == LiveDieState.DIE) {
            throw new ManageException("用户已删除");
        }
        return login(user);
    }

    @ResponseBody
    @RequestMapping(path = "login-code", method = RequestMethod.POST)
    public AjaxResponse login_code(String key) {
        AjaxResponse ajaxResponse = new AjaxResponse(true);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String userId = ops.get(key);
        if (userId != null) {
            User u = userRepository.findOne(Long.valueOf(userId));
            if (u == null) {
                return ajaxResponse.setMsg("扫描出错");
            }
            return login(u);
        } else {
            return ajaxResponse.setMsg("还未扫描");
        }
    }

    @Autowired
    private UserRoleRepository userRoleRepository;

    public AjaxResponse login(User u) {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = new SessionUser();
        UserOrganiza organiza = null;
        if (u.type == UserType.TEACHER) {
            su.setAdminUserId(u.id);
            su.setPhone(u.phone);
            su.setId(u.id);
            su.setName(u.name);
            su.setNumber(u.number);
            su.setType(u.type);
            su.setParentId(u.parentId == null ? u.id : u.parentId);

            List<UserRoleType> types =
                    userRoleRepository.findTypeByUserIdAndState(su.getId(), LiveDieState.LIVE);
            su.setRoleTypes(jsonMapper.fromJson(jsonMapper.toJson(types), List.class));
            ajax.setObj("/v2/index/index");
        } else {
            if (u.type == UserType.STUDY) {
                organiza = userOrganizaRepository.findByRegUserId(u.id);
            } else {
                organiza = userOrganizaRepository.findByUserId(u.id);
            }
            if (organiza != null && organiza.state == VerifyState.LIVE) {
                User org = userRepository.findOne(organiza.userId);
                if (org == null || org.state == LiveDieState.DIE) {
                    su.setId(u.id);
                    session.setAttribute("user", su);
                    return ajax.setObj("/org/acc/authentication");
                }
                User user = userRepository.findOne(organiza.regUserId);
                if (user != null && !StringUtils.isEmpty(user.phone)) {
                    su.setPhone(user.phone);
                }
                su.setAdminUserId(org.id);
                su.setId(org.id);
                su.setName(org.name);
                su.setNumber(org.number);
                su.setType(org.type);
                su.setParentId(org.parentId == null ? org.id : org.parentId);
                List<UserRoleType> types =
                        userRoleRepository.findTypeByUserIdAndState(su.getId(), LiveDieState.LIVE);
                su.setRoleTypes(jsonMapper.fromJson(jsonMapper.toJson(types), List.class));
                ajax.setObj("/v2/index/index");
            } else {
                su.setId(u.id);
                session.setAttribute("user", su);
                ajax.setObj("/org/acc/authentication");
            }
        }
        session.setAttribute("user", su);
        return ajax;
    }

}


